

package cate.game.framework.index;

import lombok.Data;
import lombok.ToString;
import org.springframework.data.annotation.Transient;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ToString
@Data
public class IndexedMap<INDEXED_KEY, INDEXED_VALUE> {

    private Map<INDEXED_KEY, INDEXED_VALUE> valueMap;

    @Transient
    private final Map<String, Map<INDEXED_KEY, INDEXED_VALUE>> indexMap;

    public IndexedMap() {
        this.valueMap = new ConcurrentHashMap<>();
        this.indexMap = new ConcurrentHashMap<>();
    }

    public void addValue(INDEXED_KEY key, INDEXED_VALUE value) {
        this.valueMap.put(key, value);
    }

    public void addIndex(String indexedName, INDEXED_KEY key, INDEXED_VALUE value) {
        Map<INDEXED_KEY, INDEXED_VALUE> map = this.indexMap.computeIfAbsent(indexedName, s -> new ConcurrentHashMap<>());
        map.put(key, value);
    }

    public Map<INDEXED_KEY, INDEXED_VALUE> getIndex(String indexName) {
        return indexMap.computeIfAbsent(indexName, m -> new ConcurrentHashMap<>());
    }

    public void clear() {
        this.valueMap.clear();
        this.indexMap.clear();
    }
}
